<template>
	<view class="repair-container">
		<view class="repair-header">
			<view class="repair-title">在线报修</view>
			<view class="repair-subtitle">请填写以下信息，我们将尽快为您安排维修</view>
		</view>
		
		<view class="repair-form">
			<!-- 报修类型选择 -->
			<view class="form-item">
				<view class="form-label">报修类型</view>
				<picker mode="selector" :range="repairTypes" @change="onTypeChange">
					<view class="picker-value">
						{{ repairTypes[selectedType] || '请选择报修类型' }}
						<uni-icons type="down" size="20" color="#bbb"></uni-icons>
					</view>
				</picker>
			</view>
			
			<!-- 维修优先级选择 -->
			<view class="form-item">
				<view class="form-label">维修优先级</view>
				<view class="priority-options">
					<view 
						v-for="(item, index) in priorityOptions" 
						:key="index"
						:class="['priority-item', selectedPriority === index ? 'selected' : '']"
						@click="onPrioritySelect(index)"
					>
						<text class="priority-icon" :class="item.icon"></text>
						<text class="priority-name">{{ item.name }}</text>
						<text class="priority-desc">{{ item.desc }}</text>
					</view>
				</view>
			</view>
			
			<!-- 房屋地址选择 -->
			<view class="form-item">
				<view class="form-label">房屋地址</view>
				<view class="address-select">
					<picker mode="selector" :range="communities" @change="onCommunityChange">
						<view class="picker-value">{{ communities[selectedCommunity] || '选择小区' }}</view>
					</picker>
					<picker mode="selector" :range="buildings" @change="onBuildingChange">
						<view class="picker-value">{{ buildings[selectedBuilding] || '选择楼栋' }}</view>
					</picker>
					<picker mode="selector" :range="units" @change="onUnitChange">
						<view class="picker-value">{{ units[selectedUnit] || '选择单元' }}</view>
					</picker>
					<picker mode="selector" :range="houses" @change="onHouseChange">
						<view class="picker-value">{{ houses[selectedHouse] || '选择房号' }}</view>
					</picker>
				</view>
			</view>
			
			<!-- 预约时间选择 -->
			<view class="form-item">
				<view class="form-label">预约时间</view>
				<picker mode="date" :start="minDate" :end="maxDate" @change="onDateChange">
					<view class="picker-value">
						{{ selectedDate || '选择日期' }}
					</view>
				</picker>
				<picker mode="selector" :range="timeSlots" @change="onTimeChange">
					<view class="picker-value">
						{{ timeSlots[selectedTime] || '选择时间段' }}
					</view>
				</picker>
			</view>
			
			<!-- 问题描述 -->
			<view class="form-item">
				<view class="form-label">问题描述</view>
				<textarea 
					class="description-input" 
					v-model="description" 
					placeholder="请详细描述需要维修的问题..."
					maxlength="200"
				></textarea>
				<view class="word-count">{{ description.length }}/200</view>
			</view>
			
			<!-- 图片上传 -->
			<view class="form-item">
				<view class="form-label">上传图片（选填）</view>
				<view class="upload-area">
					<view class="image-list">
						<view v-for="(img, index) in images" :key="index" class="image-item">
							<image :src="img.path" mode="aspectFill"></image>
							<text class="delete-btn" @click="deleteImage(index)">×</text>
						</view>
						<view class="upload-btn" @click="chooseImage" v-if="images.length < 3">
							<uni-icons type="camera" size="30" color="#999"></uni-icons>
							<text>上传图片</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 服务流程说明按钮 -->
		<view class="service-flow-link" @click="showServiceFlow">
			<uni-icons type="info" size="20" color="#4A90E2"></uni-icons>
			<text>服务流程与政策说明</text>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-btn" @click="submitRepair">提交报修</view>
		
		<!-- 服务流程弹窗 -->
		<view class="popup-mask" v-if="showPopup" @click="closeServiceFlow">
			<view class="popup-content" @click.stop>
				<view class="popup-title">服务流程与政策说明</view>
				<scroll-view scroll-y class="popup-scroll">
					<view class="popup-section">
						<view class="section-title">服务说明</view>
						<view class="section-content">
							<view class="content-item">1. 部分维修服务将由第三方服务商提供，可能会产生额外费用。</view>
							<view class="content-item">2. 维修费用将根据实际维修项目和服务商报价进行结算。</view>
							<view class="content-item">3. 维修人员上门前会提前与您联系确认。</view>
						</view>
					</view>
					<view class="popup-section">
						<view class="section-title">服务流程</view>
						<view class="section-content">
							<view class="content-item">1. 提交报修申请</view>
							<view class="content-item">2. 物业审核并分配维修人员</view>
							<view class="content-item">3. 维修人员联系确认</view>
							<view class="content-item">4. 上门维修服务</view>
							<view class="content-item">5. 服务完成确认</view>
						</view>
					</view>
					<view class="popup-section">
						<view class="section-title">注意事项</view>
						<view class="section-content">
							<view class="content-item">1. 请确保预约时间家中有人</view>
							<view class="content-item">2. 贵重物品请提前收好</view>
							<view class="content-item">3. 维修完成后请及时确认</view>
							<view class="content-item">4. 点击提交按钮代表您已阅读并同意服务流程与政策说明</view>
						</view>
					</view>
				</scroll-view>
				<view class="popup-footer">
					<view class="popup-btn" @click="closeServiceFlow">我知道了</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/util/request.js';
	
	export default {
		data() {
			return {
				repairTypes: ['水电维修', '门窗维修', '管道疏通', '家具维修', '其他'],
				selectedType: '',
				
				priorityOptions: [
					{
						name: '紧急',
						desc: '需要立即处理',
						icon: 'icon-emergency'
					},
					{
						name: '普通',
						desc: '正常维修需求',
						icon: 'icon-normal'
					},
					{
						name: '低优先级',
						desc: '可延后处理',
						icon: 'icon-low'
					}
				],
				selectedPriority: 1, // 默认选择普通优先级
				
				communities: ['智慧小区', '幸福家园', '阳光社区'],
				buildings: ['1栋', '2栋', '3栋', '4栋', '5栋'],
				units: ['1单元', '2单元', '3单元', '4单元'],
				houses: ['101', '102', '201', '202', '301', '302'],
				
				selectedCommunity: '',
				selectedBuilding: '',
				selectedUnit: '',
				selectedHouse: '',
				
				timeSlots: ['上午 (8:00-12:00)', '下午 (13:00-17:00)'],
				selectedDate: '',
				selectedTime: '',
				
				description: '',
				images: [],
				
				minDate: new Date().toISOString().split('T')[0],
				maxDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
				showPopup: false,
				hasAcceptedPolicy: false
			}
		},
		methods: {
			onTypeChange(e) {
				console.log('onTypeChange:' + e.detail.value);
				this.selectedType = e.detail.value;
			},
			onCommunityChange(e) {
				this.selectedCommunity = e.detail.value;
			},
			onBuildingChange(e) {
				this.selectedBuilding = e.detail.value;
			},
			onUnitChange(e) {
				this.selectedUnit = e.detail.value;
			},
			onHouseChange(e) {
				this.selectedHouse = e.detail.value;
			},
			onDateChange(e) {
				this.selectedDate = e.detail.value;
			},
			onTimeChange(e) {
				this.selectedTime = e.detail.value;
			},
			onPrioritySelect(index) {
				this.selectedPriority = index;
			},
			chooseImage() {
				uni.chooseImage({
					count: 3 - this.images.length,
					success: (res) => {
						// 获取临时文件路径列表
						const tempFiles = res.tempFiles;
						
						// 将File对象存入images数组
						this.images = [
							...this.images, 
							...tempFiles.map(file => ({
								path: file.path,
								file: file  // 存储原始File对象
							}))
						];
					}
				});
			},
			deleteImage(index) {
				this.images.splice(index, 1);
			},
			showServiceFlow() {
				this.showPopup = true;
			},
			closeServiceFlow() {
				this.showPopup = false;
				this.hasAcceptedPolicy = true;
			},
			async submitRepair() {
				if (!this.hasAcceptedPolicy) {
					uni.showToast({
						title: '请先阅读服务流程与政策说明',
						icon: 'none'
					});
					return;
				}
				
				if (!this.selectedType) {
					uni.showToast({
						title: '请选择报修类型',
						icon: 'none'
					});
					return;
				}
				
				if (this.selectedPriority === undefined) {
					uni.showToast({
						title: '请选择维修优先级',
						icon: 'none'
					});
					return;
				}
				
				if (!this.selectedCommunity || !this.selectedBuilding || !this.selectedUnit || !this.selectedHouse) {
					uni.showToast({
						title: '请选择完整地址',
						icon: 'none'
					});
					return;
				}
				if (!this.selectedDate || !this.selectedTime) {
					uni.showToast({
						title: '请选择预约时间',
						icon: 'none'
					});
					return;
				}
				if (!this.description) {
					uni.showToast({
						title: '请填写问题描述',
						icon: 'none'
					});
					return;
				}
				
				// TODO: 提交报修信息到服务器
				uni.showLoading({
					title: '提交中...'
				});
				
				console.log('submitRepair:' + this.selectedCommunity + ' ' + this.selectedBuilding + ' ' + 
				this.selectedUnit + ' ' + this.selectedHouse + ' ' + this.selectedType + ' ' + this.selectedPriority + ' ' + 
				this.selectedDate + ' ' + this.selectedTime + ' ' + this.description + ' ' + this.images);

				try {
					// 使用uni.uploadFile发送请求
					const res = await new Promise((resolve, reject) => {
						uni.uploadFile({
							url: 'http://192.168.31.72:9999/owner-server/owner/add/repair',
							filePath: this.images[0]?.path || '', // 仅用于微信小程序兼容
							name: 'files',
							formData: {
								communityId: parseInt(this.selectedCommunity),
								buildingId: parseInt(this.selectedBuilding),
								unitId: parseInt(this.selectedUnit),
								houseId: parseInt(this.selectedHouse),
								repairType: parseInt(this.selectedType),
								priority: parseInt(this.selectedPriority),
								repairTime: this.selectedDate + ' ' + this.timeSlots[this.selectedTime],
								description: this.description
							},
							header: {
								'token': uni.getStorageSync('token'), // 添加认证头
								'Content-Type': 'multipart/form-data'
							},
							success: (uploadRes) => {
								if (uploadRes.statusCode === 200) {
									resolve(JSON.parse(uploadRes.data));
								} else {
									reject(new Error(`请求失败，状态码: ${uploadRes.statusCode}`));
								}
							},
							fail: (err) => {
								reject(err);
							}
						});
					});

					if (res.code === 200) {
						uni.hideLoading();
						uni.showToast({ title: '提交成功', icon: 'success' });
						setTimeout(() => { uni.navigateBack(); }, 1500);
					} else {
						uni.hideLoading();
						uni.showToast({ title: res.msg, icon: 'none' });
					}
				} catch (err) {
					uni.hideLoading();
					uni.showToast({ title: '请求失败: ' + err.message, icon: 'none' });
					console.error('提交报修失败:', err);
				}
			}
		}
	}
</script>

<style>
	.repair-container {
		min-height: 100vh;
		background: #f6f8fa;
		padding-bottom: 120rpx;
	}
	
	.repair-header {
		background: linear-gradient(90deg, #4A90E2 0%, #87CEEB 100%);
		padding: 40rpx 32rpx;
		color: #fff;
	}
	
	.repair-title {
		font-size: 40rpx;
		font-weight: bold;
		margin-bottom: 12rpx;
	}
	
	.repair-subtitle {
		font-size: 24rpx;
		opacity: 0.9;
	}
	
	.repair-form {
		margin: 24rpx;
		background: #fff;
		border-radius: 24rpx;
		padding: 32rpx;
		box-shadow: 0 4rpx 16rpx rgba(74,144,226,0.08);
	}
	
	.form-item {
		margin-bottom: 32rpx;
	}
	
	.form-label {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 16rpx;
	}
	
	.picker-value {
		height: 80rpx;
		line-height: 80rpx;
		padding: 0 24rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
		font-size: 28rpx;
		color: #333;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.address-select {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 16rpx;
	}
	
	.description-input {
		width: 100%;
		height: 200rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 24rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}
	
	.word-count {
		text-align: right;
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
	}
	
	.upload-area {
		margin-top: 16rpx;
	}
	
	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}
	
	.image-item {
		width: 160rpx;
		height: 160rpx;
		position: relative;
	}
	
	.image-item image {
		width: 100%;
		height: 100%;
		border-radius: 12rpx;
	}
	
	.delete-btn {
		position: absolute;
		right: -10rpx;
		top: -10rpx;
		width: 40rpx;
		height: 40rpx;
		background: rgba(0,0,0,0.5);
		color: #fff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
	}
	
	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #999;
		font-size: 24rpx;
	}
	
	.upload-btn .iconfont {
		font-size: 48rpx;
		margin-bottom: 8rpx;
	}
	
	.service-flow-link {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 24rpx;
		color: #4A90E2;
		font-size: 28rpx;
	}
	
	.service-flow-link .iconfont {
		font-size: 32rpx;
		margin-right: 8rpx;
	}
	
	.popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.popup-content {
		width: 600rpx;
		max-height: 80vh;
		background: #fff;
		border-radius: 24rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}
	
	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		padding: 32rpx 0;
		border-bottom: 1rpx solid #eee;
	}
	
	.popup-scroll {
		flex: 1;
		max-height: calc(80vh - 180rpx);
	}
	
	.popup-section {
		margin-bottom: 32rpx;
		padding: 0 32rpx;
	}
	
	.section-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 16rpx;
	}
	
	.section-content {
		font-size: 26rpx;
		color: #666;
		line-height: 1.6;
	}
	
	.content-item {
		width: 550rpx;
		margin-bottom: 12rpx;
	}
	
	.popup-footer {
		padding: 24rpx 32rpx;
		border-top: 1rpx solid #eee;
	}
	
	.popup-btn {
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background: linear-gradient(90deg, #4A90E2 0%, #87CEEB 100%);
		color: #fff;
		font-size: 28rpx;
		border-radius: 40rpx;
	}
	
	.submit-btn {
		position: fixed;
		bottom: 40rpx;
		left: 24rpx;
		right: 24rpx;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		background: linear-gradient(90deg, #4A90E2 0%, #87CEEB 100%);
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
		border-radius: 44rpx;
		box-shadow: 0 4rpx 16rpx rgba(74,144,226,0.3);
	}
	
	.priority-options {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}
	
	.priority-item {
		display: flex;
		align-items: center;
		padding: 24rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
		border: 2rpx solid transparent;
		transition: all 0.3s;
	}
	
	.priority-item.selected {
		background: #e8f3ff;
		border-color: #4A90E2;
	}
	
	.priority-icon {
		font-size: 40rpx;
		margin-right: 16rpx;
	}
	
	.priority-name {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
		margin-right: 16rpx;
	}
	
	.priority-desc {
		font-size: 24rpx;
		color: #999;
	}
	
	.icon-emergency {
		color: #ff4d4f;
	}
	
	.icon-normal {
		color: #4A90E2;
	}
	
	.icon-low {
		color: #999;
	}
</style>
